package com.sunseagear.wind.modules.email.controller;

import com.google.common.collect.Maps;
import com.sunseagear.common.base.http.R;
import com.sunseagear.common.utils.JsonUtils;
import com.sunseagear.common.utils.StringUtils;
import com.sunseagear.wind.common.aspectj.annotation.Log;
import com.sunseagear.wind.common.aspectj.enums.LogType;
import com.sunseagear.wind.modules.email.dto.EmailSendDto;
import com.sunseagear.wind.modules.email.service.IEmailSendService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @version V1.0
 * @title 短信发送
 * @description 短信发送
 * @date 2017-06-08 12:56:37
 */
@RestController
@RequestMapping("/email/send")
@Log(title = "邮件发送")
@RequiredArgsConstructor
public class EmailSendController {

    private final IEmailSendService emailSendService;

    @PostMapping(value = "/massSendEmailByCode")
    @Log(logType = LogType.OTHER, title = "发送邮件")
    public R<Void> massSendEmailByCode(@RequestBody EmailSendDto emailSendDto) {
        try {
            String[] emails = emailSendDto.getEmail().split(",");
            for (String emailItem : emails) {
                if (!StringUtils.isEmpty(emailSendDto.getData())) {
                    Map<String, Object> datas = JsonUtils.toMap(StringEscapeUtils.unescapeHtml4(emailSendDto.getData()));
                    emailSendService.send(emailItem, emailSendDto.getCode(), datas);
                } else {
                    emailSendService.send(emailItem, emailSendDto.getCode(), Maps.newHashMap());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("邮件发送失败");
        }
        return R.success("发送成功");
    }
}
